#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
加密货币爆仓数据监控系统 - 简化版主入口
"""

import asyncio
import uvicorn
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from loguru import logger

from websocket_client import CoinankWebSocketClient
from data_processor import LiquidationDataProcessor
from api_routes import router, set_data_processor

# 创建FastAPI应用
app = FastAPI(
    title="加密货币爆仓数据监控API",
    description="实时监控和统计加密货币爆仓数据",
    version="1.0.0"
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该限制具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 全局数据处理器实例
data_processor = LiquidationDataProcessor()
websocket_client = None

# 静态文件目录配置
static_dir = Path(__file__).parent / "static"

@app.on_event("startup")
async def startup_event():
    """应用启动时的初始化"""
    global websocket_client
    logger.info("启动爆仓数据监控系统...")
    
    # 检查静态文件目录
    if not static_dir.exists():
        logger.warning(f"静态文件目录不存在: {static_dir}")
        logger.info("请先在前端目录运行 'npm run build' 构建前端应用")
    else:
        logger.info(f"静态文件目录已找到: {static_dir}")
    
    # 启动数据处理器的后台任务（清理+定期重算）
    await data_processor.start_background_tasks()
    
    # 设置API路由的数据处理器引用
    set_data_processor(data_processor)
    
    # 创建WebSocket客户端
    websocket_client = CoinankWebSocketClient(data_processor)
    
    # 启动WebSocket连接
    asyncio.create_task(websocket_client.start())
    
    logger.info("系统启动完成")

@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时的清理"""
    logger.info("关闭爆仓数据监控系统...")
    
    # 停止数据处理器的后台任务
    await data_processor.stop_background_tasks()
    
    if websocket_client:
        await websocket_client.stop()
    logger.info("系统已关闭")

# 注册API路由
app.include_router(router, prefix="/api")

# 健康检查端点
@app.get("/health")
async def health_check():
    return {
        "status": "healthy",
        "websocket_connected": websocket_client.is_connected() if websocket_client else False,
        "data_count": data_processor.get_total_records_count(),
        "frontend_available": static_dir.exists()
    }

# 手动处理静态文件请求
@app.get("/assets/{file_path:path}")
async def serve_assets(file_path: str):
    """手动处理assets目录下的静态文件"""
    file_path = Path(file_path)
    asset_file = static_dir / "assets" / file_path
    
    if asset_file.exists() and asset_file.is_file():
        return FileResponse(str(asset_file))
    else:
        logger.warning(f"静态文件未找到: {asset_file}")
        return JSONResponse({"error": "File not found"}, status_code=404)

# 处理根路径下的静态文件
@app.get("/{filename}")
async def serve_static(filename: str):
    """处理根目录下的静态文件"""
    if filename == "" or filename == "/":
        filename = "index.html"
    
    file_path = static_dir / filename
    
    if file_path.exists() and file_path.is_file():
        return FileResponse(str(file_path))
    else:
        # 如果不是文件，返回index.html用于SPA路由
        index_html = static_dir / "index.html"
        if index_html.exists():
            return FileResponse(str(index_html))
        else:
            return JSONResponse({"error": "Frontend not built"}, status_code=404)

# 根路径 - 返回 index.html
@app.get("/")
async def root():
    """根路径返回前端应用"""
    index_html = static_dir / "index.html"
    if index_html.exists():
        return FileResponse(str(index_html))
    else:
        return JSONResponse({
            "message": "Crypto Liquidation Monitor API is running",
            "frontend_status": "not_built",
            "instruction": "Please run 'npm run build' in the frontend directory"
        })

if __name__ == "__main__":
    # 配置日志
    logger.add("logs/app.log", rotation="1 day", retention="7 days")
    
    # 启动服务器
    uvicorn.run(
        "main_simple:app",
        host="0.0.0.0",
        port=8000,
        reload=False,  # 生产环境关闭热重载
        log_level="info"
    )